// routes/users.js
const express = require('express')
const router = express.Router()
const User = require('../models/User')
const LogService = require('../services/logService')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const { ACCESS_TOKEN_SECRET, REFRESH_TOKEN_SECRET } = require('../config/jwt')
const mongoose = require('mongoose')
const authMiddleware = require('../middlewares/auth')
const logMiddleware = require('../middleware/logMiddleware')

// 注册
router.post('/register', logMiddleware('register', (req) => ({
  method: 'email',
  success: true
})), async (req, res) => {
  const { username, email, password, phone } = req.body;

  try {
    const existingUser = await User.findOne({
      $or: [{ username }, { email }, { phone }]
    });

    if (existingUser) {
      return res.status(400).send({
        code: 400,
        msg: '用户名/邮箱/手机号已存在'
      });
    }

    const newUser = await User.create({
      username,
      email,
      phone,
      password
    });

    res.send({
      code: 201,
      msg: '注册成功',
      user: {
        id: newUser._id,
        username: newUser.username,
        phone: newUser.phone
      }
    });

  } catch (error) {
    console.error('注册失败:', error);
    res.status(500).send({ code: 500, msg: '服务器内部错误' });
  }
});

// 登录
router.post('/login', logMiddleware('login', (req) => ({
  method: req.body.username ? 'username' : 'phone',
  success: true
})), async (req, res) => {
  const { username, phone, password } = req.body;

  try {
    const user = await User.findOne({
      $or: [
        { username },
        { phone }
      ]
    }).select('+password');

    if (!user || !(await user.comparePassword(password))) {
      return res.status(401).send({
        code: 401,
        msg: username ? '用户名或密码错误' : '手机号或密码错误'
      });
    }

    if (!user.status) {
      return res.status(403).send({ code: 403, msg: '用户未启用' });
    }

    const accessToken = jwt.sign(
      { id: user._id.toString() },
      ACCESS_TOKEN_SECRET,
      { expiresIn: '15m' }
    );

    const refreshToken = jwt.sign(
      { id: user._id.toString() },
      REFRESH_TOKEN_SECRET,
      { expiresIn: '7d' }
    );

    // 更新用户登录状态和日志
    await user.updateLoginStatus(true);
    await user.updateOne({
      $push: {
        loginLogs: {
          ip: req.ip,
          time: new Date(),
          status: true
        }
      }
    });

    res.send({
      code: 200,
      msg: '登录成功',
      tokens: { accessToken, refreshToken }
    });

  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).send({ code: 500, msg: '服务器内部错误' });
  }
});

// 获取用户信息
router.get('/user/info', authMiddleware, logMiddleware('profile_view'), async (req, res) => {
  try {
    const userData = {
      _id: req.user._id,
      username: req.user.username,
      email: req.user.email,
      phone: req.user.phone,
      role: req.user.role,
      status: req.user.status,
      avatar: req.user.avatar,
      createdAt: req.user.createdAt
    };    
    res.status(200).json({
      code: 200,
      data: userData
    });
  } catch (error) {
    console.error('[用户信息查询错误]', error);
    res.status(500).json({
      code: 500,
      msg: '服务器内部错误',
      debug: process.env.NODE_ENV === 'development' ? error.stack : undefined
    });
  }
});

// 退出登录
router.post('/auth/logout', authMiddleware, logMiddleware('logout'), async (req, res) => {
  try {
    await User.findByIdAndUpdate(req.user._id, {
      $unset: {
        refreshToken: 1,
        refreshTokenExpires: 1
      }
    });

    // 更新用户状态
    await req.user.updateLoginStatus(false);

    res.json({
      code: 200,
      msg: '退出成功'
    });
  } catch (error) {
    console.error('[退出错误]', error);
    res.status(500).json({
      code: 500,
      msg: '服务端注销失败'
    });
  }
});

// 获取用户日志
router.get('/logs', authMiddleware, async (req, res) => {
  try {
    const { page = 1, limit = 20, action, startDate, endDate } = req.query;
    const result = await LogService.getUserLogs(req.user._id, {
      page: parseInt(page),
      limit: parseInt(limit),
      action,
      startDate: startDate ? new Date(startDate) : null,
      endDate: endDate ? new Date(endDate) : null
    });
    res.json({
      code: 200,
      data: result
    });
  } catch (error) {
    console.error('[获取用户日志失败]', error);
    res.status(500).json({
      code: 500,
      msg: '获取日志失败'
    });
  }
});

// 批量导入用户
router.post('/import', async (req, res) => {
  const users = req.body.users.map(u => ({
    ...u,
    password: bcrypt.hashSync(u.password, 8)
  }))
  await User.insertMany(users)
  res.send({ code: 200, msg: '导入成功' })
})

// 分页查询用户
router.post('/pagelist', async (req, res) => {
  const { pageSize, currentPage, searchTxt } = req.body
  const query = searchTxt ? {
    $or: [
      { username: { $regex: searchTxt, $options: 'i' } },
      { email: { $regex: searchTxt, $options: 'i' } }
    ]
  } : {}

  const list = await User.find(query)
    .skip((currentPage - 1) * pageSize)
    .limit(pageSize)
  const total = await User.countDocuments(query)

  res.send({ code: 200, list, total })
})

// 修改用户信息（状态/角色）
router.post('/edit', async (req, res) => {
  const { _id, ...updateData } = req.body
  await User.findByIdAndUpdate(_id, updateData)
  res.send({ code: 200, msg: '更新成功' })
})

// 手机号+验证码登录（可选扩展）
router.post('/login/mobile', async (req, res) => {
  const { mobile, verifyCode } = req.body;

  // 验证短信验证码（需要集成短信服务，这里假设已验证）
  const isCodeValid = await verifySmsCode(mobile, verifyCode);  // 需自行实现
  if (!isCodeValid) {
    return res.status(401).send({ code: 401, msg: '验证码错误' });
  }

  // 查询用户（不存在时自动注册或提示）
  let user = await User.findOne({ mobile });
  if (!user) {
    // 可选：自动创建新用户（根据业务需求）
    user = await User.create({
      mobile,
      username: `user_${mobile}`,  // 自动生成用户名
      password: bcrypt.hashSync('默认密码', 8)  // 需设置初始密码或标记为无密码用户
    });
  }

  // 生成访问令牌
  const accessToken = jwt.sign(
    { id: user._id },
    ACCESS_TOKEN_SECRET,
    { expiresIn: '15m' }
  )

  // 生成刷新令牌
  const refreshToken = jwt.sign(
    { id: user._id },
    REFRESH_TOKEN_SECRET,
    { expiresIn: '7d' }
  )

  // 加密存储刷新令牌
  const hashedRefreshToken = await bcrypt.hash(refreshToken, 8)

  // 更新用户记录
  await user.updateOne({
    refreshToken: hashedRefreshToken,
    refreshTokenExpires: new Date(Date.now() + 7 * 24 * 3600 * 1000),
    $push: {
      loginLogs: {
        ip: req.ip,
        time: new Date(),
        status: true
      }
    }
  })

  res.send({
    code: 200,
    msg: '验证码登录成功',
    tokens: {
      accessToken,
      refreshToken
    }
  })
})

// 获取用户列表
router.get('/list', async (req, res) => {
  try {
    const users = await User.find();
    res.send({ code: 200, list: users });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).send({ code: 500, msg: '服务器内部错误' });
  }
});

module.exports = router